<!-- @format -->

<template>
  <section class="todoapp">
    <Todo_Header @addTodo="addTodo" />
    <Todo_Main :todoList="toggleTodo" @delTodo="delTodo" @isAll="isAll" />
    <todo_footer :todoList="toggleTodo" @clear="clear" @toggle="toggle" />
  </section>
</template>

<script>
import todo_footer from "./components/Todo-footer.vue";
import Todo_Main from "./components/Todo-Main.vue";
import Todo_Header from "./components/Todo-Header";
// 从 styles 目录下导入相关样式
import "./styles/base.css";
import "./styles/index.css";
export default {
  components: {
    todo_footer,
    Todo_Main,
    Todo_Header,
  },
  name: "App",
  data() {
    return {
      // 待办任务列表
      todoList: JSON.parse(localStorage.getItem('todoList')) || [
        { id: 100, name: "抽烟", done: true },
        { id: 101, name: "喝酒", done: true },
        { id: 102, name: "改bug", done: false },
      ],
      active: 0,
    };
  },
  methods: {
    // 添加任务
    addTodo(name) {
      this.todoList.push({
        id: this.todoList.length
          ? this.todoList[this.todoList.length - 1].id + 1
          : 100,
        name,
        done: false,
      });
      // console.log(this.todoList);
    },
    // 删除功能
    delTodo(i) {
      this.todoList.splice(i, 1);
    },
    // 判断是否全选
    isAll(flag) {
      this.todoList.forEach((item) => (item.done = flag));
    },
    // 清空所有已完成
    clear() {
      this.todoList = this.todoList.filter((item) => !item.done);
    },
    // 切换
    toggle(active) {
      this.active = active;
    },
  },
  computed: {
    // 切换不同的数组
    toggleTodo() {
      if (this.active === 0) {
        return this.todoList;
      } else if (this.active === 1) {
        return this.todoList.filter((item) => !item.done);
      } else if (this.active === 2) {
        return this.todoList.filter((item) => item.done);
      }
    },
  },
  watch : {
    toggleTodo : {
      deep : true,
      handler() {
        localStorage.setItem('todoList',JSON.stringify(this.toggleTodo))
      }
    }
  }
};
</script>
